import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# 设置字体以支持中文
plt.rcParams['font.sans-serif'] = ['SimHei']  # 使用黑体
plt.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题


class ShowGantryFlow:
    def __init__(self, path):
        self.path = path
        self.data = None

    def show(self):
        # 提取数据
        keys = list(self.data.keys())
        mean_speeds = [d['up_flow'] for d in self.data.values() if 'up_flow' in d]
        time1s = [d['down_flow'] for d in self.data.values() if 'down_flow' in d]

        # 创建图形和坐标轴
        fig, ax = plt.subplots()
        # 绘制柱状图
        bar_width = 0.35
        indices = np.arange(len(keys))

        # 第一组柱状图
        # rects1 = ax.bar(indices, mean_speeds, bar_width, label='上游流量')
        # # 第二组柱状图
        # rects2 = ax.bar(indices + bar_width, time1s, bar_width, label='下游流量')
        # 第一组柱状图
        rects1 = ax.plot(indices, mean_speeds, marker='o', linestyle='-', color='r', label='上游流量')
        # 第二组柱状图
        rects2 = ax.plot(indices, time1s, marker='o', linestyle='-', color='b', label='下游流量')


        # 在柱子上添加数据标签
        def add_labels(rects):
            for rect in rects:
                height = rect.get_height()
                ax.annotate('{}'.format(height),
                            xy=(rect.get_x() + rect.get_width() / 2, height),
                            xytext=(0, 3),  # 3 points vertical offset
                            textcoords="offset points",
                            ha='center', va='bottom')

        # add_labels(rects1)
        # add_labels(rects2)

        # 设置 x 轴的刻度和标签，每隔12个显示一次
        ticks = indices[::12]  # 每隔12个索引选取一个
        tick_labels = keys[::12]  # 对应的标签也每隔12个选取一个

        # 添加标签和标题
        ax.set_xlabel('时间（秒）')
        ax.set_ylabel('流量（辆）')
        ax.set_title('上下游流量分布数据统计')
        ax.set_xticks(ticks)
        # ax.set_xticks(ticks + bar_width / 2)
        ax.set_xticklabels(tick_labels)
        ax.legend(loc='upper left')

        # # 叠加折线图
        # diff = [d['rate'] for d in data.values() if 'rate' in d]
        # ax2 = ax.twinx()  # 创建第二个y轴
        # ax2.plot(indices, diff, marker='o', linestyle='-', color='r', label='Rate')
        # ax2.set_ylabel('Flow Diff')  # 我们假设这是趋势线的数据
        # ax2.legend(loc='upper right')

        # 显示图表
        plt.show()

    def get_data(self):
        df_up = pd.read_csv(self.path)
        data0 = df_up.to_dict(orient='records')
        print(data0)
        self.data = {}
        for i in range(len(data0)):
            time = data0[i]['time'].split(' ')[1][:5]
            self.data[time] = {
                "total_flow": data0[i]['total_flow'],
                "up_flow": data0[i]['up_flow'],
                "down_flow": data0[i]['down_flow'],
                "flow_diff": data0[i]['flow_diff'],
                # "rate": data0[i]['down_flow'] / data0[i]['up_flow']
            }
        print(self.data)



if __name__ == '__main__':

    # A区中度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240131\all_flow_data1.csv'
    # A区重度1
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240207\all_flow_data1.csv'
    # A区重度2
    # path = r'D:\GJ\项目\事故检测\output\G004251002000620010,G004251001000320010-20240219\all_flow_data1.csv'
    # A区重度3
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240205\all_flow_data1.csv'
    # A区轻度1
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240117\all_flow_data1.csv'
    # path = r'D:\GJ\项目\事故检测\output\G004251001000310010,G004251002000610010-20240330\all_flow_data1.csv'


    # B区
    # path = r'D:\GJ\项目\事故检测\output\G004251001000210010,G004251001000310010-20240421\all_flow_data1.csv'
    # path = r'D:\GJ\项目\事故检测\output\G004251001000320010,G004251001000220010-20240502\all_flow_data1.csv'
    # 其他
    # path = r'D:\GJ\项目\事故检测\output\G004251001000210010,G004251001000310010-20240101\all_flow_data1.csv'

    # C区
    # path = r'D:\GJ\项目\事故检测\output\G004251001000120020,G004251001000120010-20240416\all_flow_data1.csv'

    name = "G004251002000620010,G004251001000320010-20240429"
    path0 = r'D:\GJ\项目\事故检测\output\邻垫高速'
    path = os.path.join(path0, name, 'all_flow_data.csv')

    showGantryFlow = ShowGantryFlow(path)
    showGantryFlow.get_data()
    showGantryFlow.show()

